const config = require("../config/config");
const udpDbModel = require("../model/updDbModel");

//负责聊天socket.io事件 绑定处理模块
const chatServer = require("./chatServer");
// const getCookie = require("../utils/cookie");

//导入操作client的数据模型
// const clientModel = require("../model/chatClientModel");

//引入串口模块
// var SerialPort = require("serialport");

// 1.串口监听处理
//获取端口列表
// var serialPort = require("serialport");
// serialPort.list(function (err, ports) {
//   ports.forEach(function(port) {
//     console.log(port.comName);
//     console.log(port.pnpId);
//     console.log(port.manufacturer);
//   });
// });

//Opening a Port 设置串口参数
// var serialPort = new SerialPort(config.com, {
//     //波特率，可在设备管理器中对应端口的属性中查看
//     baudRate: 11520,
//     autoOpen: false,
//     dataBits: 8, //数据位
//     parity: 'none', //奇偶校验
//     stopBits: 1, //停止位
//     flowControl: false
// });

// 2.UDP服务构建及监听
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
const clientSocket = dgram.createSocket("udp4");

server.bind(config.udpPort);
server.on("close", () => {
    console.log("socket已关闭");
});

server.on("error", (err) => {
    console.log("udp服务错误", err);
});

server.on("listening", () => {
    var address = server.address();
    // console.log('socket正在监听中...');
    console.log(
        "UDP server listening in " + address.address + ":" + address.port
    );

    // 3.socket服务启动
    chatServer.on("connection", (socket) => {
        console.log("UDP_socket:", socket.handshake.headers.referer);

        let json = {
            data: { msg: "后端服务器启动成功，收到客户端连接请求！" },
            from: "uid",
            sid: "sid",
            kf: "null",
            nick: "server_nick " || "小萝莉x",
            time: new Date().getTime(),
        };
        socket.emit("clinet-frist-push", json);

        socket.on("disconnect", (res) => {
            // serverModel.updateServerStatus(uid, socket.id).then((res) => { console.log('更新客服离线名单', res.insertId); });
            console.log("离线了", res);
        });

        socket.on("user-message", (msg) => {
            //返回的数据变量不能加括号 否则msg没有数据
            console.log("收到客户端信息：", msg);
            let hex16 = Bytes2HexString(msg.content);
            // console.log("收到数据转16进制：", hex16)

            //发送UDP数据给UDP客户端
            // console.log("udpclinet：",udpClientPort,updClientIP)
            //监听指定地址以及端口
            //第一个参数是发送数据，第二个参是位端口号，第三个参数为ip地址
            // clientSocket.send(msg.content, udpClientPort || 7000, updClientIP || "192.168.0.100")
            // var message = new Buffer(msg.content);  0,message.length
            let str16 = Hexstring2btye(msg.content)
            let strs = msg.content.split(" "); //将一个十六进制报文转为字符数组
            console.log("16-hex:", str16, "strs:", strs)

            // for (let i = 0; i < strs.length; i++) {
            //     strs[i] = "0x" + strs[i];
            // } 
            //每个字符加上0x
            // for (let i = 0; i < str16.length; i++) {
            //     str16[i] = "0x" + str16[i];
            // } //每个字符加上0x

            // let buffer16 = Buffer.from(str16)
            // console.log("buffer16:", buffer16)
            let buffer = Buffer.from(strs); //将数组放到buffer
            // let hex163 = new Buffer(strs, 'base64').toString('hex');
            // clientSocket.send(str16, udpClientPort, updClientIP); //发送buffer
            clientSocket.send(strs, udpClientPort, updClientIP, function(
                err,
                bytes
            ) {
                if (err) {
                    console.log("udp发送错误：", err);
                }
            });

            console.log(
                "发送到设备UPD客户端：","\n",
                msg.content, "\n",
                // buffer16, "\n",
                buffer, "\n",
                // hex163, "\n",
                str16, "\n",
                udpClientPort, "\n",
                updClientIP
            );
        });

        // 2.UDP服务构建及监听消息事件
        let updClientIP;
        let udpClientPort;
        server.on("message", (msg, rinfo) => {
            var rfidData = `${msg}`;
            let hex162 = Bytes2HexString(msg);
            let h16_hex = Bytes2HexString2(msg)

            console.log(
                `receive message from ${rinfo.address}:${rinfo.port} msg:${msg} hex16:${hex162} byte:${h16_hex}`
            );
            // server.send('exit', rinfo.port, rinfo.address)
            // console.log(`收到UDP端口数据：${msg}`)
            updClientIP = rinfo.address;
            udpClientPort = rinfo.port;
            // console.log('UDP_rfidData:', rfidData)
            socket.emit("server-message-push", rfidData);
        });

        //   启动端口监听
        //1.串口启动Opening a Port
        //连接串口后进行写入指令操作 端口打开状态监听
        // serialPort.open(function (err) {
        //     console.log("comIsOpen:", serialPort.isOpen);
        //     if (serialPort.isOpen) {
        //         console.log("serialPort:", serialPort.path);
        //     }
        //     console.log("ComOpen!err:", err);
        //     //写出数据
        //     serialPort.write("4002FEC0", function (err, results) {
        //         // console.log('comSend?err ' + err);
        //         // console.log('comSendResults ' + results);
        //     });

        // });

        //指令监听
        // serialPort.on("data", function (data) {
        //     console.log("串口", serialPort.path, "收到数据: ", data);
        //     var str = String.fromCharCode(data)
        //     var str2 = String(data)
        //     console.log("串口", serialPort.path, "收到字符串数据: ", str);
        //     console.log("串口", serialPort.path, "收到字符串数据2: ", str2);
        //     let hex16 = Bytes2HexString(data);
        //     console.log("串口", serialPort.path, "收到16进制数据：", hex16);
        //     // let str3 = hexToString(data)
        //     // console.log("串口", serialPort.path, "收到字符串数据3: ", str3);
        // });

        //串口错误监听
        // serialPort.on("error", function (error) {
        //     console.log("error: " + error);
        // });

        //  * byte型转换十六进制
        const Bytes2HexString2 = (b) => {
            let hexs = "";
            for (let i = 0; i < b.length; i++) {
                let hex = (b[i]).toString(16);
                if (hex.length === 1) {
                    hexs = '0' + hex;
                }
                hexs += hex.toUpperCase();
            }
            return hexs;
        }

        // 字节数据转16进制字符串处理函数
        const Bytes2HexString = (b) => {
            //获取十六进制数据
            let hexs = "";
            for (let i = 0; i < b.length; i++) {
                let hex = b[i].toString();
                if (hex.length === 1) {
                    hexs = "0" + hex;
                }
                hexs += hex.toUpperCase();
            }
            return hexs;
        };

        //  16进制字符串转字节型
        const Hexstring2btye = (str) => {
            let pos = 0;
            let len = str.length;
            if (len % 2 != 0) {
                return null;
            }
            len /= 2;
            let hexA = new Array();
            for (let i = 0; i < len; i++) {
                let s = str.substr(pos, 2);
                let v = parseInt(s, 16);
                hexA.push(v);
                pos += 2;
            }
            return hexA;
        }


    });
});